package com.meiming.smartfloatball;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Collections;
import java.util.List;

public class TopFloatService extends Service implements OnClickListener,OnKeyListener{
    private static final String TAG = TopFloatService.class.getSimpleName();

    WindowManager wm = null;
    WindowManager.LayoutParams ballWmParams = null;
    WindowManager.LayoutParams pointerParams = null;
    private View pointerView;
    private View ballView;
    private View menuView;
    private View listAppView;
    private float mTouchStartX;
    private float mTouchStartY;
    private float x;
    private float y;
    private RelativeLayout menuLayout;
    private Button floatImage;
    private PopupWindow pop;
    private PopupWindow listApps;
    private LinearLayout menuTop;
    private boolean ismoving = false;

    private long startTime;
    private float lastX;
    private float lastY;

    private ListView mListView = null ;
    private PackageManager mPackageManager = null ;
    private List<ResolveInfo> mAllApps =  null ;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG,"On Create");
        //加载辅助球布局
        ballView = LayoutInflater.from(this).inflate(R.layout.floatball, null);
        floatImage = (Button)ballView.findViewById(R.id.float_image);
        setUpFloatMenuView();
        setUpListApps();
        createView();

    }

    public void setUpListApps() {
        mPackageManager = getPackageManager();
        listAppView = LayoutInflater.from(this).inflate(R.layout.floatapps, null);

        mListView = (ListView)listAppView.findViewById(R.id.list_apps);
        getAllApps();

        mListView.setAdapter(new AppsAdapter(this, mPackageManager , mAllApps));
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ResolveInfo res = mAllApps.get(position);
                //得到该应用的包名和activity
                String pkg = res.activityInfo.packageName ;
                String cls = res.activityInfo.name ;

                ComponentName mComponentName = new ComponentName(pkg, cls);
                Intent intent = new Intent();
                intent.setComponent(mComponentName);
                startActivity(intent);
            }
        });
    }

    public void getAllApps() {
        //设置一个Intent的action和category为需要显示
        Intent intent = new Intent(Intent.ACTION_MAIN , null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        //如何条件的查出来
        mAllApps = mPackageManager.queryIntentActivities(intent, 0);
        //排序
        Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));
    }

    /**
     * 窗口菜单初始化
     */
    private void setUpFloatMenuView(){
        menuView = LayoutInflater.from(this).inflate(R.layout.floatmenu, null);
        menuLayout = (RelativeLayout)menuView.findViewById(R.id.menu);
        menuTop = (LinearLayout)menuView.findViewById(R.id.lay_main);
        menuLayout.setOnClickListener(this);
        menuLayout.setOnKeyListener(this);
        menuTop.setOnClickListener(this);

        pointerView = new TextView(this);
        pointerView.setBackground(getResources().getDrawable(R.drawable.cursor));


       /* Button btnHome = (Button)menuTop.findViewById(R.id.btnHome);
        btnHome.setOnClickListener(this);
        Button btnAnswerCall = (Button)menuTop.findViewById(R.id.btnAnserCall);
        btnAnswerCall.setOnClickListener(this);
        Button btnHangUp = (Button)menuTop.findViewById(R.id.btnHangUp);
        btnHangUp.setOnClickListener(this);
        Button btnBack = (Button)menuTop.findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        TextView btnTest = (TextView)menuTop.findViewById(R.id.btnTest);
        btnTest.setOnClickListener(this);*/
        TextView tvHome = (TextView)menuTop.findViewById(R.id.tvHome);
        TextView tvAnswerCall = (TextView)menuTop.findViewById(R.id.tvAnswerCall);
        TextView tvHangUp = (TextView)menuTop.findViewById(R.id.tvHangUp);
        TextView tvBack = (TextView)menuTop.findViewById(R.id.tvBack);
        TextView tvApps = (TextView)menuTop.findViewById(R.id.tvApps);
        TextView tvLeft = (TextView)menuTop.findViewById(R.id.tvLeft);
        TextView tvRight = (TextView)menuTop.findViewById(R.id.tvRight);
        TextView tvTouch = (TextView)menuTop.findViewById(R.id.tvTouch);
        TextView tvCamera = (TextView)menuTop.findViewById(R.id.tvCamera);
        TextView tvReboot = (TextView)menuTop.findViewById(R.id.tvReboot);


        tvHome.setOnClickListener(this);
        tvAnswerCall.setOnClickListener(this);
        tvHangUp.setOnClickListener(this);
        tvBack.setOnClickListener(this);
        tvApps.setOnClickListener(this);
        tvLeft.setOnClickListener(this);
        tvRight.setOnClickListener(this);
        tvTouch.setOnClickListener(this);
        tvCamera.setOnClickListener(this);
        tvReboot.setOnClickListener(this);


       // Button btnTouch = (Button)menuTop.findViewById(R.id.btnTouch);
        //btnTouch.setOnClickListener(this);
    }

    /**
     * 通过MyApplication创建view，并初始化显示参数
     */
    private void createView() {
        wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
       // wm = (WindowManager) getApplicationContext().getSystemService("window");
        ballWmParams =  ((MyApplication) getApplication()).getMywmParams();
        //ballWmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        ballWmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        ballWmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        ballWmParams.gravity = Gravity.START;
        ballWmParams.x = 0;
        ballWmParams.y = 0;
        ballWmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        ballWmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        ballWmParams.format = PixelFormat.RGBA_8888;

        pointerParams = ((MyApplication) getApplication()).getMyPointerParams();
        pointerParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        pointerParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        pointerParams.gravity = Gravity.CENTER;
        pointerParams.x = 0;
        pointerParams.y = 0;
        pointerParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        pointerParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        pointerParams.format = PixelFormat.RGBA_8888;

        //添加显示层
        wm.addView(ballView, ballWmParams);
        wm.addView(pointerView, pointerParams);

        //注册触碰事件监听器
        floatImage.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                x = event.getRawX();
                y = event.getRawY();
                Log.i(TAG, "ScreenX="+x+" ,ScreenY="+y+", LocalX="+event.getX()+", LocalY="+event.getY()+", ACTION="+event.getAction());
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        ismoving = false;
                        mTouchStartX = event.getX();
                        mTouchStartY = event.getY();

                        startTime = System.currentTimeMillis();

                        lastX=x;
                        lastY=y;
                        break;
                    case MotionEvent.ACTION_MOVE:

//                        if (!ismoving) {
//                            mTouchStartX = event.getX();
//                            mTouchStartY = event.getY();
//                        }

                        if(Math.abs(lastX-x)>5 || Math.abs(lastY-y)>5){
                            ismoving = true;
                            updateViewPosition();
                        }

                        break;
                    case MotionEvent.ACTION_UP:

                        long end = System.currentTimeMillis() - startTime;
                        // 双击的间隔在 300ms以下
                        if (end < 300) {
                            //closeDesk();
                            ismoving=false;
                        }else {
                            updateViewPosition();
                        }

                        mTouchStartX = mTouchStartY = 0;
                        break;
                }
                //如果拖动则返回false，否则返回true
               /* if(ismoving == false){
                    return false;
                }else{
                    return true;
                }*/
                return ismoving;
            }

        });
        //注册点击事件监听器
        floatImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWin();
            }
        });
    }

    public void showPopupWin(){
        DisplayMetrics dm = getResources().getDisplayMetrics();
        Log.i(TAG,"width="+dm.widthPixels+", height="+dm.heightPixels);
        pop = new PopupWindow(menuView, dm.widthPixels, dm.heightPixels);
        pop.showAtLocation(ballView, Gravity.START, 0, 0);
        pop.update();
    }

    public void showListApps(){
        DisplayMetrics dm = getResources().getDisplayMetrics();
        Log.i(TAG,"width="+dm.widthPixels+", height="+dm.heightPixels);
        listApps = new PopupWindow(listAppView, dm.widthPixels, dm.heightPixels);
        listApps.showAtLocation(pointerView, Gravity.END, 0, 0);
        listApps.update();
    }

    public void hidePopupWin(){
        if(pop!=null && pop.isShowing()){
            pop.dismiss();
        }
        if(listApps!=null && listApps.isShowing()){
            listApps.dismiss();
        }
    }

    /**
     * 更新view的显示位置
     */
    private void updateViewPosition() {
        ballWmParams.x = (int) (x - mTouchStartX);
        ballWmParams.y = (int) (y - mTouchStartY)-640;
        pointerParams.y = ballWmParams.y+(ballView.getHeight()-pointerView.getHeight())/2;
        wm.updateViewLayout(ballView, ballWmParams);
        wm.updateViewLayout(pointerView, pointerParams);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onClick(View v) {
        Log.i(TAG, "click="+v.getId());
        switch (v.getId()) {
            case R.id.lay_main:
                Log.i(TAG, "click --> lay_maim");
                Toast.makeText(getApplicationContext(), "111", Toast.LENGTH_SHORT).show();
                hidePopupWin();
                break;
            case R.id.tvHome:
                Log.i(TAG, "click --> btnHome");
                ActionController.keyHome();
                hidePopupWin();
                break;
            case R.id.tvAnswerCall:
                Log.i(TAG, "click --> btnAnserCall");
                ActionController.keyCall();
                hidePopupWin();
                break;
            case R.id.tvHangUp:
                Log.i(TAG, "click --> btnHangUp");
                ActionController.keyEndCall();
                hidePopupWin();
                break;
            case R.id.tvBack:
                ActionController.keyBack();
                break;
            case R.id.tvApps:
               // ActionController.startApp();
                startApp(AppsConfig.PKG_DING_DING);
                break;
            case R.id.tvLeft:
                pointerParams.x -= 20;
                wm.updateViewLayout(pointerView,pointerParams);
                break;
            case R.id.tvRight:
                pointerParams.x += 20;
                wm.updateViewLayout(pointerView,pointerParams);
                break;

            case R.id.tvTouch:
                hidePopupWin();
                pointerView.setVisibility(View.GONE);
                ActionController.click(pointerParams.x+360-pointerView.getWidth()/2-1, pointerParams.y+640-1);
                pointerView.setVisibility(View.VISIBLE);
                Log.i(TAG, "PointerView:width = "+pointerView.getWidth() +" , height = " + pointerView.getHeight());
                Log.i(TAG, "Pointer:Click: x = "+(pointerParams.x+360)+", y = "+(pointerParams.y+640));
                break;
            case R.id.tvCamera:
                ActionController.keyCamera();
                break;

            case R.id.tvReboot:
                ActionController.reboot();
                break;

           // case R.id.btnTouch:
               // hidePopupWin();
               // showListApps();
                //break;

            default:
                hidePopupWin();
                break;
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Toast.makeText(getApplicationContext(), "keyCode:"+keyCode, Toast.LENGTH_SHORT).show();
        switch (keyCode) {
            case KeyEvent.KEYCODE_HOME:
                pop.dismiss();
                break;
            default:
                break;
        }
        return true;
    }

    public void startApp(String packageName){
        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
        startActivity(LaunchIntent);
    }
}
